package com.ciwong.epaper.modules.epaper.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.application.PlayerParams;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.widget.ListenSpeakPlayerBottomUI;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.File;
import java.io.IOException;

/**
 * 听说模考的视频讲解
 * Created by neo on 2016/7/25.
 */
public class ListenSpeakVideoActivity extends BaseActivity implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener,
        MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnVideoSizeChangedListener {

    public static final String TAG = "ListenVideo";
    public static final String KEY_RECORDER_PATH = "KEY_RECORDER_PATH";
    public static final String KEY_PLAY_TYPE = "KEY_PLAY_TYPE";
    public static final String KEY_TITLE = "KEY_TITLE";
    public static final String KEY_QUE_STEM = "KEY_QUE_STEM";

    private ListenSpeakPlayerBottomUI player_bottom_progress;

    /**
     * 0 不需要录音
     * 1 需要录音
     */
    private int mPlayType = EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NO_NEED_RECORD;

    private Display currDisplay;
    private SurfaceView surfaceView;
    private SurfaceHolder holder;
    private MediaPlayer player;
    private boolean isSurfaceDestroyed = true;
    private Bundle mBundle;
    private int mPlayMode;
    private ImageView img_micro_recording;
    private String mRecorderPath;// 录音路径
    private View handle_player_bottom;
    private String mLoacalVideoResPath;

    private TextView tx_record_time;

    /**
     * 新需求全部走api 评测，所以要另外录音文件
     */
    protected Mp3Recorder mp3Recorder;
    protected boolean isRecordFail = false;
    private Handler timeCountHandler = new Handler();
    private String mTitle;

    private RelativeLayout video_parent_view;

    private double mVolume = -1.0;

    private TextView que_sem;

    private String bigQueStem;

    private ImageView btn_exit_fullscreen;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情
            if (player != null && player.isPlaying()) {
                player_bottom_progress.setTextTimer(player.getCurrentPosition(), player.getDuration());


                if (mPlayType == EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NEED_RECORD) {
                    int timeCount = (player.getDuration() - player.getCurrentPosition()) / 1000;
                    Spannable span = new SpannableString(getString(R.string.tip_timer2, getString(R.string.answer_audio), String.valueOf(timeCount)));
                    span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tx_record_time.setText(span);
                }


                position = player.getCurrentPosition();
            }
            timeCountHandler.postDelayed(this, 1000);
        }
    };

    private Handler mRecorderHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                    img_micro_recording.setVisibility(View.VISIBLE);
                    Drawable drawable = img_micro_recording.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable).start();
                    }

                    break;
                case Mp3Recorder.MSG_DB:// 录音分贝
                    Bundle b = msg.getData();
//                    Log.d(TAG, "###########Mp3Recorder.MSG_DB############" + Mp3Recorder.MSG_DB);
                    if (b != null) {
                        double db = b.getDouble("db");
                        if (db >= 0) {
                            Log.d(TAG, "###########db############" + db);
                            mVolume = db;
                        }
//                        Log.d(TAG, "###########db############" + db);

//                        if (microRecording != null && !Double.isNaN(db)) {
//                            microRecording.setRms(db);
//                        }
                    }
                    break;
                case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_AUDIO_RECORD############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    DialogUtil.showSettingPermissions(ListenSpeakVideoActivity.this);
                    break;

                case Mp3Recorder.MSG_ERROR_REC_START:
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_REC_START############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);

                    DialogUtil.showSettingPermissions(ListenSpeakVideoActivity.this);
                    break;
                case Mp3Recorder.MSG_REC_STOPPED:// 录音结束

                    img_micro_recording.setVisibility(View.GONE);
                    Drawable drawable2 = img_micro_recording.getDrawable();
                    if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable2).stop();
                    }
                    break;
                default:
                    break;
            }
        }

    };


    @Override
    protected int setView() {
        return R.layout.activity_listen_speak_video;
    }

    @Override
    protected void findViews() {
        img_micro_recording = (ImageView) findViewById(R.id.img_micro_recording);
        handle_player_bottom = findViewById(R.id.handle_player_bottom);
        surfaceView = (SurfaceView) findViewById(R.id.video_surface);
        player_bottom_progress = (ListenSpeakPlayerBottomUI) findViewById(R.id.player_bottom_progress);

        tx_record_time = (TextView) findViewById(R.id.tx_record_time);
        video_parent_view = (RelativeLayout) findViewById(R.id.video_parent_view);

        que_sem = (TextView) findViewById(R.id.que_sem);
        btn_exit_fullscreen = (ImageView) findViewById(R.id.btn_exit_fullscreen);


    }


    @Override
    protected void initEvent() {
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                dealBack();
            }
        });
    }


    @Override
    protected void init() {
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        registListenerHome();
//        createPhoneListener();
//        hideTitleBar();
        Intent intent = getIntent();
        if (intent != null) {
            mBundle = intent.getBundleExtra(IntentFlag.INTENT_FLAG_OBJ);
            if (mBundle == null) {
                Toast.makeText(this, "no data", Toast.LENGTH_LONG).show();
                return;
            } else {
                mPlayMode = mBundle.getInt(PlayerParams.KEY_PLAY_MODE, -1);
                mPlayType = mBundle.getInt(KEY_PLAY_TYPE);
            }

            bigQueStem = intent.getStringExtra(KEY_QUE_STEM);
        }

        mTitle = getIntent().getStringExtra(KEY_TITLE);

        setTitleText(mTitle);
        CWLog.d(TAG, "###### mBundle.getString(PlayerParams.KEY_PLAY_VUID)#######" + mBundle.getString(PlayerParams.KEY_PLAY_VUID));
        CWLog.d(TAG, "###### mBundle.getString(PlayerParams.KEY_PLAY_UUID)#######" + mBundle.getString(PlayerParams.KEY_PLAY_UUID));
        mLoacalVideoResPath = ESystem.getPackagesPath() + File.separator + mBundle.getString(PlayerParams.KEY_PLAY_VUID);

//        mLoacalVideoResPath="/storage/emulated/0/DCIM/Camera/VID_20171010_151024.mp4";

        Log.d(TAG, "######mLoacalVideoResPath#######" + mLoacalVideoResPath);

        if (mPlayType == EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NEED_RECORD) {
            mRecorderPath = mBundle.getString(KEY_RECORDER_PATH);
            CWLog.d(TAG, "######mRecorderPath#######" + mRecorderPath);
            handle_player_bottom.setVisibility(View.VISIBLE);
            que_sem.setVisibility(View.GONE);
            //录音停止，回传所需要数据
            player_bottom_progress.disableFullScreen();
            startRecord();
        } else {
            handle_player_bottom.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(bigQueStem)) {
                que_sem.setText(bigQueStem);
            }
            que_sem.setVisibility(View.VISIBLE);
        }
        //给SurfaceView添加CallBack监听
        holder = surfaceView.getHolder();
        holder.addCallback(new SurfaceCallback());
        //为了可以播放视频或者使用Camera预览，我们需要指定其Buffer类型
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //下面开始实例化MediaPlayer对象
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnInfoListener(this);
        player.setOnSeekCompleteListener(this);
        player.setOnVideoSizeChangedListener(this);
        Log.v("Begin:::", "surfaceDestroyed called");
        //然后指定需要播放文件的路径，初始化MediaPlayer
        try {
            player.setDataSource(mLoacalVideoResPath);
            Log.d(TAG, "surfaceDestroyed called");
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "IllegalArgumentException");
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Log.d(TAG, "IllegalStateException");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "IOException");
            e.printStackTrace();
        }
        //然后，我们取得当前Display对象
        currDisplay = this.getWindowManager().getDefaultDisplay();
        timeCountHandler.postDelayed(runnable, 1000);//每一秒执行一次runnable


        player_bottom_progress.setOnFullScreenListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //变成竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //变成横屏了
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            }
        });

        btn_exit_fullscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //变成竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });
    }

    @Override
    protected void loadData() {

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //变成横屏了
            hideTitleBar();
            que_sem.setVisibility(View.GONE);
            setVideoParams(player, true);


        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            showTitleBar();
            //变成竖屏了
            setVideoParams(player, false);
            if (mPlayType != EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NEED_RECORD) {
                que_sem.setVisibility(View.VISIBLE);
            }

        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (isRecordFail) {
            //录音停止，回传所需要数据
            isRecordFail = false;
            File file = new File(mRecorderPath);
            if (file.exists()) {
                file.delete();
            }
            startRecord();
            position = 0;
        }

        //解决锁屏继续播放问题
        if (!isSurfaceDestroyed && null != player) {
            play(position);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != player) {
            player.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (!isSurfaceDestroyed) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != player) {
            player.stop();
            player.release();
        }


        mRecorderHandler.removeCallbacksAndMessages(null);
        timeCountHandler.removeCallbacks(runnable);
    }

//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        super.onConfigurationChanged(newConfig);
//
//    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //变成竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            dealBack();
        }

    }

    /**
     * 返回
     */
    private void dealBack() {

        showConfirmEndDialog();
    }

    /**
     * 退出提示框
     */
    private void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_back_work);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(R.string.str_confirm,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                Intent intent = new Intent();
                                intent.putExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, IntentValue.STATE_EXIT_BY_USER);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        })
                .show();
    }


    private void startRecord() {
        CWLog.d(TAG, "开始录音");
        mp3Recorder = new Mp3Recorder(mRecorderPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.start();
    }


    /**
     * 录音失败提示框
     */
    private void showRecordFailDialog() {
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.evaluate_audio_device_retry);
        dialog.setCancelable(false);
        dialog.setPositiveButton(R.string.retry,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setNegativeButton(R.string.go_back,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        dialog.dismiss();
                        AudioPlayer.getInstance().stop();
                        finish();
                    }
                })
                .show();
    }


    @Override
    public void onVideoSizeChanged(MediaPlayer arg0, int width, int height) {
        // 当video大小改变时触发
        //这个方法在设置player的source后至少触发一次
        Log.d(TAG, "onVideoSizeChanged called");

    }

    @Override
    public void onSeekComplete(MediaPlayer arg0) {
        // seek操作完成时触发
        Log.d(TAG, "onSeekComplete called");
    }


    @Override
    public boolean onInfo(MediaPlayer player, int whatInfo, int extra) {
        // 当一些特定信息出现或者警告时触发
        switch (whatInfo) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                break;
            case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                break;
            case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                break;
        }
        return false;
    }

    @Override
    public boolean onError(MediaPlayer player, int whatError, int extra) {
        Log.d(TAG, "onError called");

        switch (whatError) {
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                Log.d(TAG, "MEDIA_ERROR_SERVER_DIED");
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                Log.d(TAG, "MEDIA_ERROR_UNKNOWN");
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer player) {
        // 当MediaPlayer播放完成后触发
        Log.d(TAG, "onComletion called");
        //播放完成停止录音
        if (isRecordFail) {

            Log.d(TAG, "##### if (isRecordFail)##### ");
            return;
        }

        if (mPlayType == EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NEED_RECORD && null != mp3Recorder) {
            mp3Recorder.stop();

            //录音失败，因为部分手机没有录音失败回调，只能靠音量是否大于0判断
            if (mVolume < 0) {
                Log.d(TAG, " mVolume < 0  ");
                return;
            }
        }
        //录音停止，回传所需要数据
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();

    }

    private int position;

    private final class SurfaceCallback implements Callback {

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        public void surfaceCreated(SurfaceHolder holder) {

            isSurfaceDestroyed = false;

            if (mLoacalVideoResPath != null) {
                play(position);
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            isSurfaceDestroyed = true;
            try {
                if (player.isPlaying()) {
                    position = player.getCurrentPosition();
                    player.stop();
                    player.reset();
                    player.release();
                }
            } catch (Exception e) {

            }
        }
    }

    private void play(int position) {
        try {
            player.reset();
            player.setDataSource(mLoacalVideoResPath);
            player.setDisplay(surfaceView.getHolder());
            player.prepare();//缓冲
            player.setOnPreparedListener(new PrepareListener(position));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final class PrepareListener implements MediaPlayer.OnPreparedListener {
        private int position;

        public PrepareListener(int position) {
            this.position = position;
        }

        public void onPrepared(MediaPlayer mp) {
            setVideoParams(mp, false);
            player.start();
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            if (position > 0) player.seekTo(position);
        }
    }


    /**
     * 设置SurfaceView的参数
     *
     * @param mediaPlayer
     * @param isLand
     */
    public void setVideoParams(MediaPlayer mediaPlayer, boolean isLand) {
        //获取surfaceView父布局的参数
        ViewGroup.LayoutParams rl_paramters = video_parent_view.getLayoutParams();
        //获取SurfaceView的参数
        ViewGroup.LayoutParams sv_paramters = surfaceView.getLayoutParams();
        //设置宽高比为16/9
        float screen_widthPixels = getResources().getDisplayMetrics().widthPixels;
        float screen_heightPixels = screen_widthPixels * 0.75f;

        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();

        //取消全屏
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (isLand) {
            screen_heightPixels = getResources().getDisplayMetrics().heightPixels;
            //设置全屏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

            btn_exit_fullscreen.setVisibility(View.VISIBLE);
        } else {
            btn_exit_fullscreen.setVisibility(View.GONE);
        }
        float screen_por = screen_widthPixels / screen_heightPixels;
        float video_por = (float) videoWidth / (float) videoHeight;
        if (screen_por > video_por) {
            sv_paramters.height = (int) screen_heightPixels;
            sv_paramters.width = (int) (screen_heightPixels * video_por);
        } else {
            //16:9  19:9
            sv_paramters.width = (int) screen_widthPixels;
            sv_paramters.height = (int) (screen_widthPixels / video_por);
        }
        rl_paramters.width = (int) screen_widthPixels;
        rl_paramters.height = (int) screen_heightPixels;
        //获取MediaPlayer的宽高
        video_parent_view.setLayoutParams(rl_paramters);
        surfaceView.setLayoutParams(sv_paramters);
    }


    /**
     * 监听电话
     */
    private void createPhoneListener() {
        try {
            TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new OnPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class OnPhoneStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    break;

                case TelephonyManager.CALL_STATE_RINGING:
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, TelephonyManager.CALL_STATE_RINGING);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:

                    break;
            }

            super.onCallStateChanged(state, incomingNumber);
        }
    }

    @Override
    public void onHomeKeyPressed() {
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, TelephonyManager.CALL_STATE_RINGING);
        setResult(RESULT_OK, intent);
        finish();
    }

}
